package com.kr.aia.powerrp.db;

import java.util.ArrayList;
import java.util.List;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

public class UserDBUtil {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private Context context;
	
	private String[] allColumns = { MySQLiteHelper.COLUMN_USER_ID, 
									MySQLiteHelper.COLUMN_USER_NAME, 
									MySQLiteHelper.COLUMN_USER_PHONE_NO
								   };
	
	public UserDBUtil(Context context) {
		dbHelper = new MySQLiteHelper(context);
		this.context = context;
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}
	
	
	public UserInfoVO insertUserInfo(UserInfoVO userInfo, UserInfoVO orgUserInfo ) {
		//기존 정보 삭제 후 입력
		deleteUser();
		
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_USER_NAME, userInfo.getUserName());
		values.put(MySQLiteHelper.COLUMN_USER_PHONE_NO, userInfo.getUserPhoneNo());
		
		long insertId = database.insert(MySQLiteHelper.TABLE_USER, null, values);
		
		// To show how to query
		Cursor cursor = database.query(MySQLiteHelper.TABLE_USER,
				allColumns, MySQLiteHelper.COLUMN_USER_ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		
		if(insertId > -1){
			Toast.makeText(context, "저장 되었습니다.", Toast.LENGTH_LONG).show();
		}else{
			Toast.makeText(context, "저장 실패!!", Toast.LENGTH_LONG).show();	
		}
		
		return cursorToUserInfo(cursor);
	}
	
	

	
	
	
	public void deleteUser(){
		database.delete(MySQLiteHelper.TABLE_USER, null, null);
	}
	

	public UserInfoVO getAllData() {
		UserInfoVO userInfo = null;
		Cursor cursor = database.query(MySQLiteHelper.TABLE_USER, allColumns, null, null, null, null, null);
		if(cursor.getCount() > 0){
			cursor.moveToFirst();
		
			userInfo = cursorToUserInfo(cursor);
			cursor.moveToNext();
		}
		cursor.close();
		
		return userInfo;
	}

	private UserInfoVO cursorToUserInfo(Cursor cursor) {
		UserInfoVO userInfo = new UserInfoVO();
		
		userInfo.setSeqno(cursor.getString(0));
		userInfo.setUserName(cursor.getString(1));
		userInfo.setUserPhoneNo(cursor.getString(2));
		
		return userInfo;
	}
}